<template>
  <div id="fileTable">
    <el-table ref="filetable" size="small" v-show="listVisible" element-loading-text="拼命加载中"
              :data="fileList"
              v-loading="listLoading"
              @selection-change="selsChange"
              style='font-family:"宋体"'
              width='100%'>
      <el-table-column type="selection" width="80"></el-table-column>
      <el-table-column prop="fileName" width="400" label="文件名">
        <template slot-scope="scope">
          <div class="folder-box" @click="handleCellClick(scope.row)">
            <div style="display: flex;align-items: center">
              <span :class="'file-icon '+scope.row.iconcls"></span>
              <el-tooltip
                class="item"
                effect="dark"
                v-if="scope.row.fileName && $abslength(scope.row.fileName) > 32"
                :content="scope.row.fileName"
                placement="top-start"
              >
                <span class="file-name">{{ scope.row.fileName.substring(0,$getFontShowLength(scope.row.fileName,32))+'...'}}</span>
              </el-tooltip>
              <span v-else class="file-name">{{scope.row.fileName}}</span>
            </div>
            <div class="folder-box-options" v-if="scope.row.fileType == 0">
              <span style="cursor: pointer; padding-right: 10px" @click.stop @click="downloadFile(scope.row)">
                <i class="fa fa-cloud-download" aria-hidden="true"></i>下载
              </span>
                <span style="cursor: pointer; padding-right: 10px" @click.stop @click="previewFile(scope.row)" v-show='isshow !=="我的文档"'>
                <i class="fa fa-file" aria-hidden="true"></i>预览
              </span>
              <span style="cursor: pointer; padding-right: 10px" @click.stop @click="handleDelete(scope.row)"  v-show='isshow=="我的文档"'>
                <i class="fa fa-trash-o" aria-hidden="true"></i>
                删除
              </span>
              <el-popover placement="right" width="90" trigger="hover"  v-show='isshow=="我的文档"'>
                <ul class="settingOptions">
                  <li @click.stop @click="renameHandle(scope.row)" v-show='isshow=="我的文档"'>
                    <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                    重命名
                  </li>
                  <li @click.stop @click="previewFile(scope.row)">
                    <i class="fa fa-file" aria-hidden="true"></i>
                    文件预览
                  </li>
                  <li @click.stop @click="fileHistory(scope.row)" v-show='isshow=="我的文档"'>
                    <i class="fa fa-history" aria-hidden="true"></i>
                    历史记录
                  </li>
                  <li @click.stop @click="shareFile(scope.row)"  v-show='isshow=="我的文档"'>
                    <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    内部分享
                  </li>
                  <li @click.stop @click="OutShareFile(scope.row)"  v-show='isshow=="我的文档"'>
                    <i class="fa fa-file" aria-hidden="true"></i>
                    外链分享
                  </li>
                  <li @click.stop @click="companyShare(scope.row)"  v-show='isshow=="我的文档"'>
                    <i class="fa fa-share-square-o" aria-hidden="true"></i>
                    公司分享
                  </li>
                  <li @click.stop @click="partnerShare(scope.row)"  v-show='isshow=="我的文档"'>
                    <i class="fa fa-share" aria-hidden="true"></i>
                    合作伙伴分享
                  </li>
                  <li @click.stop @click="fileMove(scope.row)"  v-show='isshow=="我的文档"'>
                    <i class="fa fa-arrows" aria-hidden="true"></i>
                    移动文件
                  </li>
                </ul>
                <i slot="reference" class="el-icon-more-outline" style="cursor: pointer; font-weight: bold" @click.stop></i>
              </el-popover>
            </div>
            <div class="folder-box-options" v-else-if="scope.row.fileType == 1 && isshow=='我的文档'">
              <span style="cursor: pointer; padding-right: 10px" @click.stop @click="renameHandle(scope.row)">
                <i class="fa fa-pencil-square-o" aria-hidden="true"></i>重命名
              </span>
              <span style="cursor: pointer; padding-right: 10px" @click.stop @click="handleDelete(scope.row)">
                <i class="fa fa-trash-o" aria-hidden="true"></i>
                删除
              </span>
              <el-popover placement="right" width="90" trigger="hover">
                <ul class="settingOptions">
                  <li @click.stop @click="shareFile(scope.row)">
                    <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    内部分享
                  </li>
                  <li @click.stop @click="OutShareFile(scope.row)">
                    <i class="fa fa-file" aria-hidden="true"></i>
                    外链分享
                  </li>
                  <li @click.stop @click="companyShare(scope.row)">
                    <i class="fa fa-share-square-o" aria-hidden="true"></i>
                    公司分享
                  </li>
                    <li @click.stop @click="partnerShare(scope.row)"  v-show='isshow=="我的文档"'>
                        <i class="fa fa-share" aria-hidden="true"></i>
                        合作伙伴分享
                    </li>
                  <li @click.stop @click="fileMove(scope.row)"  v-show='isshow=="我的文档"'>
                    <i class="fa fa-arrows" aria-hidden="true"></i>
                    移动文件
                  </li>
                </ul>
                <i slot="reference" class="el-icon-more-outline" style="cursor: pointer; font-weight: bold" @click.stop></i>
              </el-popover>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="creatTime" label="创建日期" min-width></el-table-column>
      <el-table-column prop="updateTime" label="操作日期" min-width></el-table-column>
      <el-table-column prop="size" label="大小" min-width>
        <template slot-scope="scope">
          <span v-if="scope.row.fileType == 1">-</span>
          <span v-else>{{scope.row.size}}</span>
        </template>
      </el-table-column>
      <!--收藏-->
      <el-table-column width='80'>
        <template slot-scope="scope" v-show="scope.row.isFavorites!=undefined">
          <el-button
            class="butt"
            size="mini"
            type="text"
            v-show="scope.row.isFavorites==0 && (isshow == '我的文档' || isshow == '同事共享')"
            @click="collectFile(scope.row)"
            >
            <i class="fa fa-star-o" aria-hidden="true" ></i>
          </el-button>
          <el-button
            class="butt"
            size="mini"
            type="text"
            v-show="scope.row.isFavorites==1 && (isshow == '我的文档' || isshow == '同事共享')"
            @click="collectFile(scope.row)"
            style="margin-left:0"
            >
            <i class="fa fa-star" aria-hidden="true" ></i>
          </el-button>
          <el-popover
                    placement="top-start"
                    trigger="hover"
                    popper-class="resave"
                    width="160"
          >
              <div style="text-align: center">
                <span>转存到我的文档</span>
              </div>
              <el-button
                      slot="reference"
                      v-if="isshow!='我的文档'&&scope.row.isFavorites!=undefined"
                      class="butt"
                      size="mini"
                      @click="retweet(scope.row)"
                      style="margin-left:10px"
                      type="text">
                <i class="fa fa-retweet" aria-hidden="true"></i>
              </el-button>
            </el-popover>
        </template>
      </el-table-column>
      <el-table-column min-width>
        <template slot-scope="scope">
          <div v-if="$store.state.loadingList.length>0&&$store.state.loadingList[0].id==scope.row.id">
            <span>正在下载中：&nbsp;</span>
            <span style="color:red" @click="stopDownload"><i class='el-icon-circle-close'></i></span>
            <el-progress :percentage='$store.state.loadingList[0].percentComplete'></el-progress>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from 'axios';
var xhr = new XMLHttpRequest();
  export default {
    inject: ['reloadFilesTableData', 'setExpandedKeys'],
    props: ['filesTableData', 'nodeData'],
    provide() {
      return {
        handleCellClick: this.handleCellClick
      }
    },
    data() {
      return {
        listVisible: true,
        fileList: [],
        listLoading: false,
        sels: [], // 列表选中列
        isshow:sessionStorage.getItem("currentBox"),
      }
    },
    created() {
    },
    mounted() {
      console.log(this.filesTableData);
      this.handleFileList(this.filesTableData);
    },
    methods: {
    reloadData(data){
      console.log(data);
      this.$http.post("/file/clickdir", {
        id: data
      }).then(res=>{
        if(res.status == 200 && res.data !== null){
            this.handleFileList(res.data);
            console.log(res.data);
        }
      })
    },
    retweet(para) {
       this.$emit("retweet",para);
     },
     fileMove(row) {
       console.log(row)
       if(row!=null){
         this.$refs.filetable.clearSelection();
         this.sels=[];
         if(Array.isArray(row)){
           this.sels=[].concat(row);
         }else{
           this.sels.push(row);
         }
       }
       console.log(this.sels);
       console.log('filetable-filemove')
       this.$emit("fileMove",this.sels);
     },
      companyShare(item){
        this.$emit("companyShare",item);
      },
      handleDelete(item){
        this.$emit("handleDelete",item);
      },
      renameHandle(item) {
        this.$emit("renameHandle",item);
      },
      fileHistory(item){
        this.$emit("fileHistory",item);
      },
      previewFile(item){
        this.$emit("previewFile",item);
      },
      OutShareFile(item){
        this.$emit("outShareFile",item);
      },
      partnerShare(item){
        this.$emit("partnerShare",item);
      },
      shareFile(item){
        this.$emit("shareFile",item);
      },
      downloadFile(file) {
        let methodType=file.fileSize>1000000000 ? 0 : 1;
      if(this.$store.state.ipfsArray==0){
        this.$message.error('获取请求路径失败,请检查网络或呼叫管理员');
      }else{
        if(methodType){
          if(this.$store.state.loadingList.length>0){
          this.$message.warning('请等待当前文件下载完成后，再执行下载操作。');
          return;
        }
        this.$store.commit('setFileListDownBox',1);
        let obj={
        id:file.id,
        percentComplete:0
      }
      this.$store.commit('setLoadingList',[obj]);
           this.getBlob(this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash).then(blob => {
             this.$store.commit('setLoadingList',[]);
             this.$store.commit('setFileListDownBox',0);
          this.saveAs(blob, file.fileName,true);
        });
        }else{
          let url=this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash;
          console.log(url);
          this.saveAs(url,file.fileName);
          this.$message({
            type:'warning',
            message:'大文件需专用通道匿名加速下载，下载后请手动重命名',
            duration:'5000'
          })
        }
      }
    },
    getType(filename) {
        var index1 = filename.lastIndexOf(".");
        var index2 = filename.length;
        var type = filename.substring(index1 + 1, index2);
        return type;
      },
    getBlob(url) {
      let _this=this
      return new Promise(resolve => {
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        let obj=this.$store.state.loadingList[0];
        xhr.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        obj.percentComplete =  Math.round((evt.loaded / evt.total ).toFixed(2) * 100);
        _this.$store.commit('setLoadingList',[obj]);
      }
    }, false);
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };
        xhr.send();
      });
    },
    stopDownload(){
      xhr.abort();
      this.$message.info('取消下载');
      this.$store.commit('setLoadingList',[]);
      this.$store.commit('setFileListDownBox',0);
    },
    saveAs(url,filename,isArr) {
      if (window.navigator.msSaveOrOpenBlob && isArr===true) {
        navigator.msSaveBlob(url, filename);
      } else {
        const link = document.createElement("a");
        const body = document.querySelector("body");
        if(isArr===true){
         link.href=window.URL.createObjectURL(url);
        }else{
          link.href = url;
        };
        link.type="application/octet-stream"
        link.download = filename;
        console.log(link.download)
        link.style.display = "none";
        console.log(link)
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    },
      collectFile(row) {
        let message;
        if (row.isFavorites == 0) {
          message = "是否确认收藏文件" + row.fileName;
        } else {
          message = "是否取消收藏" + row.fileName;
        }
        this.$confirm(message, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.$http.get("/favorites/clickCollection", {
            params: {
              id: row.id
            }
          }).then(res => {
            if (res.status == 200) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              if (row.isFavorites == 0) {
                row.isFavorites = 1;
              } else {
                row.isFavorites = 0;
              }
              this.$emit("changeFilesTableData",this.filesTableData,row)
              for(let i in this.fileList){
                console.log("aaaaaaaaa");
                if(this.fileList[i].id == row.id){
                  this.$set(this.fileList[i],"isFavorites",row.isFavorites);
                  break;
                }
              }
            } else {
              this.$message.error("操作失败");
            }
          });
        })
      },
      handleFileList(data) {
        let file_icon = '';
        this.fileList = [];
        for (let i = 0; i < data.length; i++ ) {
          if (data[i].fileName == null) {
            continue;
          }
          let suffixTemp = data[i].fileName.split(".");
          if (suffixTemp.length > 1) {
            suffixTemp = suffixTemp[suffixTemp.length - 1];
            file_icon = "icon_list_" + suffixTemp;
          } else if (data[i].fileType === 0) {
            suffixTemp = "";
          } else {
            suffixTemp = null;
          }
          if(data[i].isFavo != undefined){
            data[i].isFavorites = data[i].isFavo;
          }
          this.fileList.push({
            id: data[i].id,
            dirId: data[i].dirId,
            fileName: data[i].fileName,
            size: this.$getFileSize(data[i].fileSize),
            creatTime: data[i].creatTime == null ? "暂无数据" : data[i].creatTime,
            updateTime: data[i].updateTime == null ? "暂无数据" : data[i].updateTime,
            suffix: suffixTemp,
            fileHash: data[i].fileHash,
            fileType: data[i].fileType,
            iconcls: data[i].fileType == 1 ? "icon_list_folder" : file_icon,
            isFavorites: data[i].isFavorites,
            realName: data[i].realName,
            fileSize:data[i].fileSize,
          });
        }
        console.log(this.fileList);
        this.$emit("changeBigdata",this.fileList);
      },
      clearSelection(){
        this.$refs.filetable.clearSelection();
        console.log(this.$parent);
      },
      handleCellClick(row) {
        if (row.fileType == 1) {
          this.setExpandedKeys({row, nodeData: this.nodeData})
        }else{
          this.$emit("previewFile",row);
        }
      },
      abslength(str) {
        return str.replace(/[^\x00-\xff]/ig, '**').length;
      },
      selsChange(sels) {
        this.$emit("getSels",sels);
        this.sels = sels;
      },
    }
  }
</script>
<style scoped lang="scss">
  #fileTable {
    .file-icon {
      background: url("/static/bigicon.png") no-repeat -196px 0px;
      display: inline-block;
      width: 28px;
      height: 29px;
    }
    .el-table--small td {
      padding: 12px 0 !important;
    }
    .file-name {
      margin-left: 10px;
    }
    .file-name:hover {
      text-decoration: underline;
      cursor: pointer;
    }
    .options-list span {
      color: #01b1a2;
    }
    .options-list span :hover {
      color: #f5f7fa;
    }
    .folder-box {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .folder-box-options {
      display: none;
    }
    .folder-box:hover .folder-box-options {
      height: 23px;
      display: inline-block !important;
      float: right;
      font-weight: 700;
    }
  }

</style>
